<template>
  <view class="main" @click="play(voiceData)">
    <view class="title" v-if="nowPlayKey!== playKey">
      <text class="mytext" style="color: #00ffff; font-size: 30rpx; white-space: normal">语音信息</text>
      <img class="imgs" src="/static/tool/play.png" mode="aspectFill" />
    </view>

    <view class="title" v-if="nowPlayKey === playKey">
      <view class="progress">
        <progress
          :percent="progressPercent"
          border-radius="4"
          stroke-width="8"
          active-mode="forwards"
          activeColor="#00ff00"
          backgroundColor="#EBEBEB"
          active="true"
          duration="10"
        />
      </view>
      <view class="picbox">
        <image class="nicPic" src="/static/sound.png" mode="aspectFill"></image>
      </view>
    </view>
  </view>
</template>
<script>
export default {
  name: 'voicePlay',
  props: {
    voiceData: {
      type: Object,
      required: true
    },
    playKey: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      stateConfig: {
        isSound: 1
      },
      nowPlayKey: -1,
      audioContext: null,
      nicPic: '',
      message: [],
      msglist: [],
      isPlaying: false,
      progressPercent: 0, // 新增进度百分比变量
      user: null ,// 假设这个变量存在
	  endTime:null
    };
  },
  computed: {
    newMsg() {
      return this.message.filter((item) => {
        return item.messageType === 1 && item.senderId!== this.user.userId;
      });
    }
  },
  watch: {
    newMsg: {
      handler(newValue) {

		  this.play(newValue[0]);
	 
       
      },
      deep: true // 监听对象或数组的变化
    }
  },
  created() {
    // 绑定事件监听
    this.msgListener = (res) => {
      this.message = res.data;
    };
    this.voiceListener = (res) => {
      this.play(res);
    };
    this.isSoundListener = (res) => {
      this.stateConfig.isSound = res;
      console.log(res);
    };

    uni.$on('msg', this.msgListener);
    uni.$on('voice', this.voiceListener);
    uni.$on('isSound', this.isSoundListener);
  },
  beforeDestroy() {
    // 正确解绑事件
    uni.$off('msg', this.msgListener);
    uni.$off('voice', this.voiceListener);
    uni.$off('isSound', this.isSoundListener);
  },
  methods: {
    getImageSrc() {
      // 这里的isplay变量可能需要检查是否定义正确
      // if (this.isplay!== -1 && this.msglist.length > this.isplay) {
      //   return this.msglist[this.isplay].nicPic;
      // }
      return '/static/sound.png';
    },

    play(voiceData) {
		console.log('99999999999')

      if (!voiceData ||!this.stateConfig.isSound) {
        return;
      }
      // 如果正在播放，直接返回
      if (this.isPlaying) {
        return;
      }
      this.isPlaying = true; // 标记开始播放
      this.nicPic = voiceData.nicPic;
      this.nowPlayKey = voiceData.timestamp;

      // 重置音频上下文避免事件监听重复
      if (this.audioContext) {
        console.log('1停止并重置上下文');

        try {
          this.audioContext.pause();
          this.audioContext.destroy();
          this.audioContext = null;
        } catch (e) {
          console.error("音频错误", e);
          // 可以在这里添加一些恢复操作或者提示用户
        }
      }

      // 创建新的音频实例（根据具体API调整）
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.autoplay = true;
      this.audioContext.src = voiceData.content.voicePath;

      // 绑定事件监听
      const onTimeUpdate = () => {
        const duration = voiceData.content.duration;
        if (duration > 0) {
          this.progressPercent = (this.audioContext.currentTime / duration) * 100;
        }
      };

      const onEnded = () => {
        this.isPlaying = false;
        this.nowPlayKey = -1;
        this.progressPercent = 0;
        this.nicPic = '';
      };

      const onError = (err) => {
        console.error('播放出错:', err);
        // 根据错误码进行更具体的处理
        if (err.errCode === -99) {
          console.error('音频解码失败，请检查音频文件完整性和格式:', err);
        }
        this.isPlaying = false;
        this.nowPlayKey = -1;
        this.progressPercent = 0;
      };

      this.audioContext.onTimeUpdate(onTimeUpdate);
      this.audioContext.onEnded(onEnded);
      this.audioContext.onError(onError);
      this.audioContext.onPlay(() => {
        console.log('开始播放');
      });

      this.audioContext.play();
    }
  }
};
</script>
<style lang="scss" scoped>
.main {
}

.title {
  display: flex;
  flex-direction: row;
  background-color: rgba(0, 0, 0, 0.2);
  height: 35rpx;
  width: 150rpx;
  border-radius: 17.5rpx;
  justify-items: center;
  align-items: center;
  padding: 1rpx;
}
.imgs {
  height: 35rpx;
  width: 35rpx;
  border-radius: 17.5rpx;
  background-color: white;
}
.picbox {
  display: flex;
  width: 35rpx;
  height: 35rpx;
  flex-direction: row;
  align-content: center;

  background-color: white;
  border-radius: 17.5rpx;
  margin-right: 5rpx;
}

.nicPic {
  width: 35rpx;
  height: 35rpx;
  border-radius: 15.5rpx;
}

.progress {
  flex: 1;
  margin-right: 5rpx;
}
</style>